/*
 * RoadSegment.cpp
 *
 *  Created on: Oct 25, 2009
 *      Author: jbarreneche
 */

#include "RoadSegment.h"

void orderMinMax(int *min, int *max) {
	if (*min > *max) {
		*min ^= *max;
		*max ^= *min;
		*min ^= *max;
	}
}
RoadSegment::RoadSegment(Road* road, int minHeight, int maxHeight, const Intersection origin, const Intersection destination) {
	this->road = road;
	bool inverted = minHeight > maxHeight;
	this->maxHeight = inverted? minHeight : maxHeight;
	this->minHeight = inverted? maxHeight : minHeight;
	this->origin = inverted? (new Intersection(destination)) : (new Intersection(origin));
	this->destination = inverted? (new Intersection(origin)) : (new Intersection(destination));
}

RoadSegment::~RoadSegment() {
	delete this->origin;
	delete this->destination;
}

void RoadSegment::addEdge(Edge* edge, bool increasingDirection) {
	if (increasingDirection)
		this->increasingEdges.add(0, edge);
	else
		this->decreasingEdges.add(0, edge);
}
util::LinkedList<Edge*>* RoadSegment::getIncreasingEdges() {
	return &this->increasingEdges;
}

util::LinkedList<Edge*>* RoadSegment::getDecreasingEdges() {
	return &this->decreasingEdges;
}

bool RoadSegment::overlaps(int minHeight, int maxHeight) {
	orderMinMax(&minHeight, &maxHeight);
	return this->minHeight < maxHeight && this->maxHeight > minHeight;
}

bool RoadSegment::overlapsExactly(int minHeight, int maxHeight) {
	orderMinMax(&minHeight, &maxHeight);
	return this->minHeight == minHeight && this->maxHeight == maxHeight;
}

bool RoadSegment::contains(int height) {
	return height >= minHeight && height <= maxHeight;
}

double RoadSegment::increasingPercentage(int height) {
	return (double)(height - minHeight) / (maxHeight - minHeight);
}
double RoadSegment::decreasingPercentage(int height) {
	return 1 - increasingPercentage(height);
}

